package top.dreamix.njitkit.util

import io.ktor.client.*
import io.ktor.client.call.body
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.http.URLBuilder
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
import android.util.Log as ALog

/**
 * 网络工具类，提供全局复用的 HttpClient 实例
 */
object NetworkUtil {

    /**
     * 全局复用的 HttpClient 实例
     * 使用单例模式避免重复创建连接，提高性能
     */
    val httpClient: HttpClient by lazy {
        HttpClient(CIO) {
            // 安装 JSON 序列化支持
            install(ContentNegotiation) {
                json(Json {
                    ignoreUnknownKeys = true
                    isLenient = true
                    prettyPrint = true
                })
            }

            // 安装日志记录（可选，用于调试）
            install(Logging) {
                logger = Logger.DEFAULT
                level = LogLevel.HEADERS
            }

            // 配置引擎参数
            engine {
                // 最大请求数
                maxConnectionsCount = 1000
                // 每个端点的最大请求数
                endpoint.maxConnectionsPerRoute = 100
                // 请求超时设置
                requestTimeout = 30000
            }

            // 配置默认请求头
            defaultRequest {
                header("Accept", "*/*")
                header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                header("Connection", "keep-alive")
                header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0")
            }
        }
    }

    /**
     * 在应用程序退出时关闭 HttpClient
     */
    fun close() {
        httpClient.close()
    }

    suspend fun getPortalState(): Int {
        val url = URLBuilder("http://captive.apple.com/").build()
        val responseText: String = NetworkUtil.httpClient.get(url) {
            header("Accept-Language", "")    // 未知原因导致设置了这个头的话响应无法解析为文本
        }.body()
        if (responseText.contains("Success")) return 0 // mean the portal has been connected
        if (responseText.contains("172.31.255.156")) return 1 // mean the portal is supported
        return 2  // mean the portal is not supported
    }
}

object Log {
    fun debug(s: String) {
        ALog.d("NJITKit", s)
    }

    fun info(s: String) {
        ALog.i("NJITKit", s)
    }

    fun warn(s: String) {
        ALog.w("NJITKit", s)
    }

    fun error(s: String) {
        ALog.e("NJITKit", s)
    }
}